package web

import (
	"encoding/json"
	"fmt"
	"github.com/boombuler/barcode"
	"github.com/boombuler/barcode/qr"
	"github.com/roseboy/goo"
	"image"
	"image/png"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strings"
)

type OpenController struct {
	goo.Web
	AccessToken string
}

func (web *OpenController) Controller() {
	//二维码
	web.Get("code/:u/:p", func(ctx *goo.Context) {
		u := ctx.GetPara(":u")
		p := ctx.GetPara(":p")
		token := web.GetToken(u, p)
		base64code, err := web.GetCode(token)
		if err != nil {
			web.AccessToken = ""
			token := web.GetToken(u, p)
			base64code, _ = web.GetCode(token)
		}

		code, err := qr.Encode(base64code, qr.L, qr.Unicode)
		if err != nil {
			log.Fatal(err)
		}

		if base64code != code.Content() {
			log.Fatal("data differs")
		}

		code, err = barcode.Scale(code, 300, 300)
		if err != nil {
			log.Fatal(err)
		}

		writePng("test.png", code)

		ctx.RenderFile("test.png")
	})
}

func (web *OpenController) GetCode(token string) (string, error) {
	client := &http.Client{}
	request, _ := http.NewRequest("GET", "http://118.190.142.66:9001/access_service/api/getLockQrCode", nil)

	request.Header.Add("ACCESS_TOKEN", token)
	response, _ := client.Do(request)
	defer response.Body.Close()

	body, _ := ioutil.ReadAll(response.Body)
	maps := make(map[string]interface{})
	json.Unmarshal([]byte(body), &maps)
	if maps["code"].(string) == "0" {
		return "", fmt.Errorf("token timeout")
	}
	code := maps["content"].(string)
	return code, nil
}

func (web *OpenController) GetToken(u string, p string) string {
	if web.AccessToken == "" {
		client := &http.Client{}
		request, _ := http.NewRequest("POST", "http://118.190.142.66:9001/auth_service/app/employeeLogin", strings.NewReader(fmt.Sprintf("password=%s&phone=%s", p, u)))

		request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
		response, _ := client.Do(request)
		defer response.Body.Close()

		body, _ := ioutil.ReadAll(response.Body)
		maps := make(map[string]interface{})
		json.Unmarshal(body, &maps)
		web.AccessToken = maps["content"].(map[string]interface{})["ACCESS_TOKEN"].(string)
	}
	return web.AccessToken
}

func writePng(filename string, img image.Image) {
	file, err := os.Create(filename)
	if err != nil {
		log.Fatal(err)
	}
	err = png.Encode(file, img)
	// err = jpeg.Encode(file, img, &jpeg.Options{100})      //图像质量值为100，是最好的图像显示
	if err != nil {
		log.Fatal(err)
	}
	file.Close()
	log.Println(file.Name())
}
